package com.itheima.ydd.utils;

import java.util.ArrayList;
import java.util.List;

public class TextTransUtil {

    private TextTransUtil() {

    }

    /**
     * ["fhsjlfjsl","hahhahah"]
     * 转化为
     * [\"fhsjlfjsl\",\"hahhahah\"]
     *
     * @param info
     * @return
     */
    public static String doArrayToString(String info) {
        //1.判断info中是否存在,分隔号","
        if (!info.contains(",")) {
            // 没有:代表一条数据
            StringBuffer sb = new StringBuffer(info);
            //给指定的下标去添加数据
            sb.insert(1, "\"");
            sb.insert(info.length(), "\"");
            return sb.toString();
        }
        // 有:代表多条数据--直接拼接
        //2.得到数组去进行拼接" \" "
        //利用","进行分割
        String[] split = info.split(",");
        //单独对第一个做拼接处理
        StringBuffer split1SB = new StringBuffer(split[0]);
        split1SB.insert(1, "\"");
        split1SB.insert(split[0].length() + 1, "\",");
        //单独对最后一个做拼接处理
        StringBuffer split2SB = new StringBuffer(split[split.length - 1].trim());
        split2SB.insert(0, "\"");
        split2SB.insert(split[split.length - 1].length() - 1, "\"");
        //对其他数据进行拼接处理--  fhsjlfjsl --> \"fhsjlfjsl\"
        if (split.length == 2) {
            return split1SB.toString() + split2SB.toString();
        }
        StringBuffer sb = new StringBuffer(split[1].trim());
        sb.insert(0, "\"");
        sb.insert(split[1].length(), "\",");
        //3.返回数据
        return split1SB.toString() + sb.toString() + split2SB.toString();
    }


    /**
     * [\"hahahah\"]
     * 转化为
     * ["fhsjlfjsl","hahhahah"]
     *
     * @param info
     * @return
     */
    public static List<String> doStringToArray(String info) {
        info = info.replace("[", "");
        info = info.replace("]", "");
        List<String> list = new ArrayList<>();
        // 1.判断是否有,
        if (!info.contains(",")) {
            //去除\"
            info = info.replace("\"", "");
            list.add(info);

            return list;
        }
        //2.如果有,分割数据
        String[] split = info.split(",");
        for (String s : split) {
            //去除\"
            s = s.replace("\"", "");
            list.add(s);
        }
        return list;
    }

}
